<?php
/**
 * <i>@step</i>组件
 * 
 * 循环，并可以设置步长
 * 
 * 可以使用的参数有：
 * - x-from integer 开始 
 * - x-to   integer 结束
 * - [x-step] integer 步长，默认为1
 * - [x-value] integer 存放每一步值的变量
 * 
 * 如果开始和结束都是变量，则只有x-from不大于x-to的时候有效。
 *
 * 例子： 
 * <code>
 * <ol com="@step" x-to="1" x-from="10" x-step="1" x-value="key">
 *	 <li>{$key}</li>
 * </ol>
 * </code>
 *
 * @version $Id: IMintStepComponent.php 312 2008-04-23 16:29:38Z iwind $
 * @package util.mint.component
 */
class IMintStepComponent extends IAbstractMintComponent {
	/**
	 * 取得支持的参数列表
	 *
	 * @return array
	 */	
	public function getSupportedParameters() {
		return array("x-from", "x-to", "x-step", "x-value");
	}
	
	/**
	 * 取得HTML属性映射
	 *
	 * @return array
	 * @since 0.0.3
	 */
	public function getHtmlAttrMapping() {
		return array();
	}
	
	/**
	 * 处理组件
	 *
	 * @return boolean
	 */	
	public function processComponent() {
		$parameters = $this->getParameters();
		if (!isset($parameters["x-from"]) || !isset($parameters["x-to"])) {
			return false;
		}
		
		//from
		$xFrom = IMintVariable::getDefinition($parameters["x-from"]);
		if ($xFrom == null) {
			$xFrom = intval($parameters["x-from"]);
		}
		
		//to
		$xTo = IMintVariable::getDefinition($parameters["x-to"]);
		if ($xTo == null) {
			$xTo = intval($parameters["x-to"]);
		}
		
		//step
		$xStep = 1;
		if (isset($parameters["x-step"])) {
			$xStep = IMintVariable::getDefinition($parameters["x-step"]);
			if ($xStep == null) {
				$xStep = intval($parameters["x-step"]);
			}
			if ($xStep == 0) {
				throw new IMintException("step in @step components can't be '0'");
			}
		}
		$xStep = abs($xStep);
		
		//value
		if (isset($parameters["x-value"])) {
			$xValue = IMintVariable::getDefinition($parameters["x-value"]);
			if ($xValue == null) {
				throw new IMintException("x-value in @step components must be a valid variable");
			}
		}
		else {
			$xValue = "\$i";
		}
		
		$beginText = "<?php\n";
		if (is_integer($xFrom) && is_integer($xTo)) {
			if ($xFrom >= $xTo) {
				$beginText .= "for ({$xValue}={$xFrom};{$xValue}>={$xTo};{$xValue}-={$xStep}){\n ?>";
			}
			else {
				$beginText .= " for ({$xValue}={$xFrom};{$xValue}<={$xTo};{$xValue}+={$xStep}){ \n ?>";
			}
			$endText = "<?php } ?>";
		}
		else {
			$beginText .= "if({$xFrom}<={$xTo}){\n for ({$xValue}={$xFrom};{$xValue}<={$xTo};{$xValue}+={$xStep}){ \n ?>";
			$endText = "<?php }} ?>";
		}
		
		
		$this->addAroundScript($beginText, $endText);
		
		return true;
	}
}

?>